import update from "react-addons-update";
import {treeEach} from "../utils";

const MenuReducer: object = {
    namespace: "menuReducer",
    state: {
        menuMap: {},
        menuBtnMap: {}
    },
    createMenu: function (data: any) {
        // @ts-ignore
        const {menuMap = {}}: { menuMap: any } = this.state;

        let newMenuMap: any = {};
        treeEach(data, (node: any) => {
            newMenuMap[node.id] = node.children || [];
        });
        // @ts-ignore
        return {
            ...this.state,
            menuMap: {...update(menuMap, {$merge: newMenuMap})}
        }
    },
    createMenuBtn: function (data: any) {
        // @ts-ignore
        const {menuBtnMap = {}}: { menuBtnMap: any } = this.state;

        let newMenuBtnMap: any = {};
        treeEach(data, (node: any) => {
            newMenuBtnMap[node.id] = node || {};
        });
        // @ts-ignore
        return {
            ...this.state,
            menuBtnMap: {...update(menuBtnMap, {$merge: newMenuBtnMap})}
        }
    },
    getMenuById: function (menuId: string) {
        // @ts-ignore
        return this.state.menuMap[menuId] || false
    }
};

export default MenuReducer;

